package question.solution54;

import question.SolutionTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution54 implements SolutionTemplate {

    public List<Integer> spiralOrder(int[][] matrix) {
        int size = matrix.length;
        int arrSize = matrix[0].length;
        boolean[][] checked = new boolean[size][arrSize];
        short right = 1;
        short down = 2;
        short left = 3;
        short up = 4;
        short direction = right;
        int row = 0;
        int col = 0;
        List<Integer> result = new ArrayList<>();
        do{
            result.add(matrix[row][col]);
            checked[row][col] = true;
            if(direction == right){
                if(col+1>=arrSize || checked[row][col+1]){
                    if(row+1 <= size-1 && !checked[row+1][col]){
                        row+=1;
                        direction = down;
                    }else{
                        break;
                    }
                }else{
                    col+=1;
                }
            }else if(direction == down){
                if(row+1>=size || checked[row+1][col]){
                    if(col-1 >=0 && !checked[row][col-1]){
                        col-=1;
                        direction = left;
                    }else{
                        break;
                    }
                }else{
                    row+=1;
                }
            }else if(direction == left){
                if(col-1<0 || checked[row][col-1]){
                    if(row-1 >=0 && !checked[row-1][col]){
                        row-=1;
                        direction = up;
                    }else{
                        break;
                    }
                }else{
                    col-=1;
                }
            }else if(direction == up){
                if(row-1<0 || checked[row-1][col]){
                    if(col+1 <= arrSize-1 && !checked[row][col+1]){
                        col+=1;
                        direction = right;
                    }else{
                        break;
                    }
                }else{
                    row-=1;
                }
            }
        }while(true);
        return result;
    }

    @Override
    public void test() {
        int[][] matrix = new int[1][1];
        int[] arr = {1};
        matrix[0] = arr;
        List<Integer> result = spiralOrder(matrix);
        System.out.println();
        return;
    }
}
